<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="角色名称">
                <a-input v-model="queryParam.name" placeholder="请输入角色名称"/>
              </a-form-item>
            </a-col>
          
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:addrolebtn2>新建角色</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>{return index}"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:editrolebtn2>修改</a>
            <a-divider type="vertical" />
            <a-popconfirm
              v-action:deleterolebtn2
              title="温馨提示:若该角色已经在用户身上绑定,删除后用户需重新绑定角色! 然后您确定要删除这个角色吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
              v-if="record.name!='超级管理员'&&record.name!='供应商'&&record.name!='业务员'"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        @getCheckList="getCheckList"
        @getAllList="getAllList"
        @btnChecked="btnChecked"
        @pageChecked="pageChecked"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { getRoLeList, AddRole, UpdataRole, DelRole } from '@/api/system'

import CreateForm from './modules/CreateForm'

// const userList = {
//   'data': [
//     {
//       id:1,
//       name: '管理员',
//       createtime: '2012/12/12 12:12:12',
//     },
//     {
//       id:2,
//       name: '供应商',
//       createtime: '2012/12/12 12:12:12',
//     },
//     {
//       id:3,
//       name: '业务员',
//       createtime: '2012/12/12 12:12:12',
//     },
//   ],
//   'pageSize': 10,
//   'pageNo': 0,
//   'totalPage': 6,
//   'totalCount': 57
// }

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '角色名称',
    dataIndex: 'name'
  },
  {
    title: '注册时间',
    dataIndex: 'createtime',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'roleList',
  components: {
    STable,
    CreateForm,
  },
  data () {
    this.columns = columns
    return {
      // 记录页面的数组
      pageCheckeds: [],
      // 选中的数组
      allCheckeds: [],
      // 权限列表
      roles: [],
      // 权限列表
      role: [{}],
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        // return new Promise((res, rej) => {
        //   res()
        // }).then(res => {
        //   return userList
        // })
        return getRoLeList(requestParameters)
        .then(res => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    pageChecked(value) {
      this.pageCheckeds = value
      console.log('-----------------页面------------', value)

    },
    btnChecked(value) {
      this.btnCheckeds = value
      console.log('-----------------按钮------------', value)
    },
    getAllList(value) {
      this.roles = value
    },
    // 获取权限列表
    getCheckList(value) {
      this.role = value
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
        this.confirmLoading = true
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              values.btn_role = this.btnCheckeds
              values.page_role = this.pageCheckeds
              values.owned_role = this.roles
              values.roles = this.role
              UpdataRole(values).then(res => {
                if( res ) {
                  resolve()
                } else {
                  this.confirmLoading = false
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            })
          } else {
            // 新增
            console.log('新增角色')
            new Promise((resolve, reject) => {
              values.btn_role = this.btnCheckeds
              values.page_role = this.pageCheckeds
              values.owned_role = this.roles
              values.roles = this.role
              AddRole(values).then(res => {
                if( res ) {
                  resolve()
                } else {
                  this.confirmLoading = false
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 删除
    confirm(e) {
      const form = this.$refs.createModal.form
      console.log(e);
      DelRole({id: e.id}).then(res => {
        // 重置表单数据
        form.resetFields()
        // 刷新表格
        this.$refs.table.refresh()
        this.$message.success('删除成功');
      }).catch(error => {
        console.log('-------------error------------', error)
      })
    },
    cancel(e) {
      console.log(e);
      this.$message.error('已取消');
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    // 重置
    reset () {
      const form = this.$refs.createModal.form
      this.queryParam = {}
        // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
  }
}
</script>
